<template>
  <div class="page-modal">
    <el-dialog title="新建用户" v-model="visible" width="30%" center destroy-on-close>
      <Form v-bind="modalConfig" v-model="formData"></Form>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineExpose } from 'vue'
import { useStore } from 'vuex'
import Form from '@/base-ui/form/src/Form.vue'

const props = defineProps<{
  modalConfig: any
  defaultInfo: any
  pageName: string
  otherInfo: any
}>()

const visible = ref(false)
const formData = ref<any>({})

watch(
  () => props.defaultInfo,
  (newValue: any) => {
    for (const item of props.modalConfig.formItems) {
      formData.value[`${item.field}`] = newValue[`${item.field}`]
    }
  }
)

const store = useStore()
const handleConfirmClick = () => {
  visible.value = false
  if (Object.keys(props.defaultInfo).length) {
    store.dispatch('system/editPageDataAction', {
      pageName: props.pageName,
      editData: { ...formData.value, ...props.otherInfo },
      id: props.defaultInfo.id
    })
  } else {
    store.dispatch('system/createPageDataAction', {
      pageName: props.pageName,
      newData: { ...formData.value, ...props.otherInfo }
    })
  }
}

defineExpose({
  visible
})
</script>

<style scoped lang="less"></style>
